
/*
*Pool Public Licence version 0.1 or later
*Released on 20th April 2008.
*Any voilations can be repoted at paritosh@wikiocean.net
*What is treated as voilations can be found at www.wikiocean.net/ppl1-voilations* 
******************************************************************************
* The contents of this file are subject Affero GPL v3 and later with additional conditions.
* The additional conditions are to be considered as part of the Affero GPL v3 and later.
* The additional conditions will supersede the Affero GPLv3 and later in case of conflict.
* ("License"); You may not use this file except in compliance with the License
* You may obtain a copy of the License at http://www.gnu.org/licenses/agpl.html
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* The Initial Developer of the Original Code is Paritosh Pungaliya.
* created by Paritosh Pungaliya are Copyright (C) Paritosh Pungaliya; All Rights Reserved.
* Contributions are Copyright (C) 2001-2008 Paritosh Pungaliya.

* Objective of the additional terms (license) 
* 1) Is to extend the software freedom to freedom to work.
* 2) To ensure that knowledge is free from monopoly of agencie(s).
* 3) To avoid a situation where big corporates or investors can buy out free software groups and companies and then start milking the communities built around it.
* (this trend can be seen how the openness changes in companies that get Venture Capital funding.)
* (if you agree to this logic I invite you to our group to work together)

* Additional conditions
*  0) Source code will also include
* 	a) data dictionaries, data ontologies which are used to alter the behavior of code or to control           the features of application.
* 	b) Any code generated or derived automatically or manually from this code or logic
*  1) The revenue generated by deploying, implementing , selling services and other activities
*  	 based on this source code should be shared 100%, between the people working on it.
*  2) Capital invested should be given only fixed rate of return or linked to revenue/surplus growth for limited time.
*  3) People working on the project should always have an option to replace the capital provider in full or part with lower cost capital.
*  4) Their should not be any ownership which can be sold as a claim on future profit to be generated from the work of people working on the code.
*  5) Brand thus generated should belong to the group.
*  6) For old and new members revenue sharing should be equal for same work equivalent.
*  7) The share of revenue should be decided by bidding for work before allocation of work within the group.
*  8) Before bidding various method of measuring the work should be clearly defined and published in public domain. Any change in process should also be publised in public domain imediately.
*  9) All data related to to revenue sharing should be published as and when generated in public domain.
*  10) For group of people having size more than 10 people will have to make it open online for others to participate in bids. 
*  11) All people involved in related and sub project will be treated as a group.
*  12) Once this license is being used for a certain code then all and any other software services being provided by the group should complusorilly come under 100% revenue sharing.
*  13) Cross subsidization should not happen under this revenue share, no additional benefit should be drawn from the people, by the employing agency.
*  14) Any position or knowledge or legal structure created relating to people working on code, which adversely affects the spirit of 100% revenue share will be treated as a violation.
*  15) Revenue sharing defined.
*     a) includes direct revenue and also intangible gains like brand, and organization.
*     b) No personal judgment should be involved in judging the distribution of revenue.It has to be pre-defined formula based.
*     c)100% of revenue should be shared before expenses and recievers should have control over what expenses to incur.
*     d)For the work done in any month by contributing group member, working on any project can be given revenue share from the work done by the group, for a maximum of 18 months after that month.
*     e)Revenue should be apportioned to the month in which work is done and not when received.
*  The group fulfilling the above conditions also has to be a wiki ecosystem further defined in www.wekosystem.org or read about Wekosystem at www.wikiocean.net

*  ******************************************************************************
*/  
package pricelist;


import java.awt.Point;
import java.io.File;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.text.DecimalFormat;

import timer.ExecutionTimer;
import timer.TimerRecordFile;

import com.lowagie.text.Cell;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.PageSize;
import com.lowagie.text.Element;
import com.lowagie.text.FontFactory;
import com.lowagie.text.Font;
import com.lowagie.text.Table;
//import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.rtf.RtfWriter2;

/**
 * @author Shweta
 *
 */

public class GenerateRtfFile
{	
	
		Table table;
		Document document;
		
		int heading=0;   /* sets the column no. of heading in table*/
		int count=2;     /*  sets the no. of table in a page*/
		
		 
		 /*
		  * This function sets the heading of table
		  */
        private void setHeading(String[] headingList)
        {
        	ExecutionTimer t = new ExecutionTimer();
        	t.start();
        	String []arr=headingList;
        	Font font=FontFactory.getFont(FontFactory.TIMES, 10);
        	font.setStyle(Font.BOLD);
        	try
        	{        		
	        		for(int i=0;i<arr.length;i++)
	        		{
	        			Chunk chunk = new Chunk(arr[i], font);
						Cell cell=new Cell(chunk);
	        			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
	        			table.addCell(cell,new Point(0,heading));
	        			heading++;
	        		}	        		
	        		if(heading>=(3*arr.length) )
	        				heading=0;
        	}
        	catch(Exception e)
        	{
        		
        	}
        	t.end();
    		TimerRecordFile timerFile=new TimerRecordFile("pricelist","GenerateRtfFile","setHeading",t.duration());
        	
        }
        
        
        
        /*
         * This function accepts random file as input & creates an RTF file with data in table format  
         */
        
        public void getRTFfile(RandomAccessFile random,String[] columnList,float []cellWidths,final String[] headingList,String[] categoryList,String[] formatList,String[] format)
		{	
        	ExecutionTimer t = new ExecutionTimer();
   		 	t.start();
			RandomAccessFile rafTemp=random; 		
		 	
			int [] categoryIndex=new int[categoryList.length];			
			int [] columnIndex=new int[columnList.length];	
			int [] formatIndex=new int[formatList.length];	 		
			
			/* path where rtf file is to be created*/
			String path="D:\\Registration\\Item\\CODE\\Item_A.rtf";
			
			String [] tempArray    = categoryList;
			String [] headingArray = headingList;
			float  [] headerwidths = cellWidths;
		
	 		int mainLength=0, tableWidth=mainLength=columnIndex.length;    
	 		int  x=0, y=0, row=0, column=0, lastRow=0,lastColumn=0;
	 		
	 		int totalRows=49; /*sets total no. of rows in a page*/
	 		int totalChar=20; /*sets total no. of characters in a cell*/
	 		
	 		Font font=null;
	 		Chunk chunk=null;
	 		Cell cell=null;
	 		/* creates document of given size*/
	 		document = new Document(PageSize.A4,2,36,0,0);
	 
			try
			{ 
				String temp=rafTemp.readLine();
				String[] strArr=temp.split("\t");
				
				/* creates table of given length & sets its properties*/
				 table = new Table(mainLength);
				 table.setOffset(0f);
				 table.setAlignment(Element.ALIGN_LEFT);
				 table.setAutoFillEmptyCells(true);
				 table.setCellsFitPage(true);
				 
				 /*creates rtf file on given path*/
				 RtfWriter2.getInstance(document, new FileOutputStream(path));
				 
				 /*creates pdf file on given path*/
				// PdfWriter.getInstance(document, new FileOutputStream("/home/osc1/Desktop/RTF/RTF/GeneratePdf.pdf"));
				 
				 /*opens document to write*/
				 document.open();
				
				 /* totalWidth sets total width of table*/
				 float totalWidth=0f;
				 for(int i=0;i<headerwidths.length;i++)
				 {
					 totalWidth += headerwidths[i];					 
				 }
			
			        table.setWidths(headerwidths);
			        table.setWidth(totalWidth);
			  
			        /*calls following function to get heading of table*/
			        setHeading(headingArray);
			        
			        	for(int i=0;i<columnList.length;i++)
						{
				 			for(int j=0;j<strArr.length;j++)
				 			{	 				
								if((columnList[i].trim().toLowerCase()).equals(strArr[j].trim().toLowerCase()))
								{
									/*stores indices of column list given, from input file*/	
									columnIndex[x]=j;					
										x++;
									break;
								}
				 			}
						}
				 		
				 		for(int i=0;i<categoryList.length;i++)
						{
				 			for(int j=0;j<strArr.length;j++)
				 			{	 				
								if((categoryList[i].trim().toLowerCase()).equals(strArr[j].trim().toLowerCase()))
								{
									/*stores indices of category list given, from input file*/
									categoryIndex[y]=j; 	
										y++;							
									break;
								}
				 			}
						}
				 		x=0;

				 		for(int i=0;i<formatList.length;i++)
						{
				 			for(int j=0;j<strArr.length;j++)
				 			{	 				
								if((formatList[i].trim().toLowerCase()).equals(strArr[j].trim().toLowerCase()))
								{
									/*stores indices of format list given, from input file*/
									formatIndex[x]=j; 	
										x++;							
									break;
								}
				 			}
						}
		 		row++;		 		
		 		x=y=0;
		 		
				while(rafTemp.read() != -1)
				{					
					rafTemp.seek(rafTemp.getFilePointer()-1);
					
					temp=rafTemp.readLine();				
					//System.out.println("Line is:"+temp);
					strArr=temp.split("\t");	
		
						for(int i=0;i<categoryIndex.length;i++)
						{	
							for(int j=0;j<strArr.length;j++)
							{
								if(categoryIndex[i]==j)
								{
									try
									{
										if(!(tempArray[i].trim().toUpperCase().equals(strArr[j].trim().toUpperCase())))						
										{
											try
											{
												if(strArr[j].trim().equals(""))
																break;
												tempArray[i]=strArr[j].trim().toUpperCase(); 
												
												font=FontFactory.getFont(FontFactory.TIMES, 9);
												font.setStyle(Font.BOLD);
												
												/*stores values of categories & are added to table*/												
												 chunk = new Chunk(strArr[j].trim().toUpperCase(), font);
												 cell=new Cell(chunk);
												cell.setColspan(mainLength);
												cell.setHorizontalAlignment(Element.ALIGN_CENTER);
												x=row;
												row++;
												if(row > (totalRows+1))
												{
													tableWidth=count*mainLength;
													setWidth(headerwidths);
													setHeading(headingArray);
													row=2;
												}
												
												column=table.getColumns()-mainLength;
												y=column;											
												table.addCell(cell,new Point(row-1,column));
											}
											catch (Exception e)
											{
												tempArray[i]=strArr[j].trim().toUpperCase();
												 chunk = new Chunk(strArr[j].trim().toUpperCase(),font );
												 cell=new Cell(chunk);
												cell.setColspan(mainLength);
												cell.setHorizontalAlignment(Element.ALIGN_CENTER);
												x=row;
												if(row>totalRows)
												{
													tableWidth=count*mainLength;
													setWidth(headerwidths);
													setHeading(headingArray);
													row=1;
												}
												
												column=table.getColumns()-mainLength;
												y=column;												
												table.addCell(cell,new Point(row,column));												
												row++;										
											}
											if(x==totalRows && y==(2*mainLength))
											{
												setNewPage(headingArray,headerwidths);
												row=1;
												column=lastRow=lastColumn=0;
												tableWidth=mainLength;
											}
										}									
									}
									catch(Exception e)
									{
										tempArray[i]=strArr[j].trim().toUpperCase();
										 chunk = new Chunk(strArr[j].trim().toUpperCase(),font);
										 cell=new Cell(chunk);
										cell.setColspan(mainLength);	
										cell.setHorizontalAlignment(Element.ALIGN_CENTER);
										x=row;
										if(row>totalRows)
										{
											tableWidth=count*mainLength;
											setWidth(headerwidths);
											setHeading(headingArray);
											row=1;
										}
										
										column=table.getColumns()-mainLength;
										y=column;										
										table.addCell(cell,new Point(row,column));										
										row++;										
									}
									
									break;
								}
							}
						}
					
					for(int i=0;i<columnIndex.length;i++)
					{
						for(int j=0;j<strArr.length;j++)
						{
							if(columnIndex[i]==j)
							{
								if(strArr[j].length()>totalChar)
									strArr[j]=strArr[j].substring(0,(totalChar-1));
								/*if(strArr[j].trim().equalsIgnoreCase("unit"))
									strArr[j]="uni";*/
								
								 font=FontFactory.getFont(FontFactory.TIMES, 9);
								 String s=strArr[j].trim().toLowerCase();
								
									for(int z=0;z<formatIndex.length;z++)
									{
										if(formatIndex[z]==j)
											s=setFormat(s,format[z]);
									}
								
								/*stores values of columns & are added to table*/
								  chunk = new Chunk(s+" ", font);
								  cell=new Cell(chunk);
								try
								{
									Double objD=Double.parseDouble(strArr[j]); 	
									cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
								}
								catch (Exception e)
								{
									cell.setHorizontalAlignment(Element.ALIGN_LEFT);
								}
								
								if(column < tableWidth){ column++; }
								else
								{
										if(column == table.getColumns())
										{	
												lastColumn=column;
												int a=mainLength-1;
												column=table.getColumns()-a;											
										}
										else
										{
												column=0;
												column++;
										}
										
									row++;
								}
							
								if(row<=totalRows)
								{ 
										lastRow=row;
										if(!(column <= tableWidth))
											row++;									
								} 
								else 
								{
									column=tableWidth+1;								
									tableWidth=count*mainLength;									
									setWidth(headerwidths);
									setHeading(headingArray);
									row=1;										
								}
								
							//	System.out.print("("+row+","+ (column-1)+") ,,");
								table.addCell(cell,new Point(row,column-1));
							
								break;
							}
						}	
					}
				    //System.out.println(" ");
					
					if(lastRow==totalRows && lastColumn==(3*mainLength))
					{
						setNewPage(headingArray,headerwidths);
						row=1;
						column=lastRow=lastColumn=0;
						tableWidth=mainLength;
					}
				}
				
				 document.add(table);	 
		
				document.close();			
			
			System.out.println("GenerateRtf.rtf in RTF folder is Created");
			}
			catch(Exception e){ e.printStackTrace();}
			t.end();
			TimerRecordFile timerFile=new TimerRecordFile("pricelist","GenerateRtfFile","getRTFfile",t.duration());
		}
		
		
		/*
		 * sets the total width of table if no. of columns increases
		 */		
		private void setWidth(float []headerwidths)
		{
			ExecutionTimer t = new ExecutionTimer();
			 t.start();
			try
			{
				int x=0;
				table.addColumns(headerwidths.length);
				float headerWidth[]=headerwidths;
				float tempWidth[]=new float[(count*headerWidth.length)];
				float totalWidth=0f;
				for(int i=0;i<tempWidth.length;i++ )
				{
					tempWidth[i]=headerWidth[x];
					totalWidth += tempWidth[i];
					x++;
					if(x==headerWidth.length)
							x=0;
				}
			
				table.setWidths(tempWidth);
				table.setWidth(totalWidth);
				count++;
				if(count>3)
					count=2;
			}
			catch(Exception e){	}
			
			t.end();
			TimerRecordFile timerFile=new TimerRecordFile("pricelist","GenerateRtfFile","setWidth",t.duration());
		}
		
		
		/*
		 * creates a new page whenever table size increases than limit
		 */
		private void setNewPage(String []headingArr,float []headerwidths)
		{
			ExecutionTimer t = new ExecutionTimer();
			 t.start();
			try
			{
				float headerWidth[]=headerwidths;
				int tempWidth=headerWidth.length;
				
				document.add(table);
				table.deleteAllRows();
				
				for(int i=tempWidth;i<(3*tempWidth);i++)
					table.deleteColumn(tempWidth);				
				
			        table.setWidths(headerWidth);
			        
			        float totalWidth=0f;
					 for(int i=0;i<headerWidth.length;i++)
					 {
						 totalWidth += headerWidth[i];
					 }
			        table.setWidth(totalWidth);
			        
				document.newPage();
				setHeading(headingArr);
			}
			catch(Exception e){}
			t.end();
			TimerRecordFile timerFile=new TimerRecordFile("pricelist","GenerateRtfFile","setNewPage",t.duration());
		}
	
		
		private String setFormat(String s,String f)
		{
			ExecutionTimer t = new ExecutionTimer();
			 t.start();
			String value="0.0";
			try 
			{
				value = s;
				String format=f;
				double tempvalue =Double.parseDouble(value);
				DecimalFormat de = new DecimalFormat(format);
				value = de.format(tempvalue);
			} catch (NumberFormatException e) {
			}
			t.end();
			TimerRecordFile timerFile=new TimerRecordFile("pricelist","GenerateRtfFile","setFormat",t.duration());
			return value;
		}
		
		public static void main(String[] args)
		{
			ExecutionTimer t = new ExecutionTimer();
			 t.start();
			 
			// int headerwidths[] = {17,3,4,3,6,6,5};			
			
			String path="D:\\Registration\\Item\\CODE\\Grocerry.csv";					
			
			/*columnList must match to column names of input file*/
			String[] columnList={"Short_name","itemcode","measurment","Buy","Sell","Mrp"};
			
			/* categoryList contains column names on which category is to be created.*/
			String[] categoryList={"Category"};
			
			/* order of values in columnList & headingList must be same */
			String[] headingList={"Item","Cod","Qty","Buy","Sell","Mrp"};
			
			/*order of widths in cellWidths must be according to headingList*/
			float [] cellWidths={15.1f,3.4f,3,5,4.6f,4};
			
			/*formatList contains column names on which formatting is to be done */
			String []formatList={"buy","sell","mrp"};
			
			/*sets format of formatList*/
			String []format={"0.0","0.0","0"};	
			
			File file=new File(path);
			GenerateRtfFile rtfObj=new GenerateRtfFile();
			try
			{
				RandomAccessFile random = new RandomAccessFile(file,"rw");
				rtfObj.getRTFfile(random,columnList,cellWidths,headingList,categoryList,formatList,format);
			}
			catch(Exception e){}
			t.end();
			TimerRecordFile timerFile=new TimerRecordFile("pricelist","GenerateRtfFile","main",t.duration());
		}


}

